package com.heima.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.PageResult;
import com.heima.pojo.Sku;
import com.heima.pojo.dto.SkuDto;
import com.heima.pojo.vo.SkuVo;
import com.heima.service.ISkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/vm-service/sku")
@Api(tags = "商品管理")
public class SkuController {
    @Autowired
    private ISkuService skuService;

    @PostMapping
    @ApiOperation("添加商品")
    public Boolean addSku(@RequestBody SkuDto skuDto) {
        if (ObjectUtil.isEmpty(skuDto)) {
            return false;
        }
        skuDto.setCreateTime(LocalDateTime.now());
        skuDto.setUpdateTime(LocalDateTime.now());
        return skuService.save(BeanUtil.toBean(skuDto, Sku.class));
    }

    @GetMapping("/search")
    @ApiOperation("分页查询商品列表")
    public PageResult<SkuVo> search(PageResult<SkuVo> pageResult, @RequestParam(required = false) String skuName) {
        return skuService.search(pageResult, skuName);
    }

    @PutMapping("{skuId}")
    @ApiOperation("修改商品")
    public Boolean updateSku(@PathVariable Long skuId, @RequestBody SkuDto skuDto) {
        if (ObjectUtil.isEmpty(skuDto) || ObjectUtil.isEmpty(skuId)) {
            return false;
        }
        skuDto.setUpdateTime(LocalDateTime.now());
        LambdaUpdateWrapper<Sku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Sku::getSkuId, skuId);
        return skuService.update(BeanUtil.toBean(skuDto, Sku.class), updateWrapper);
    }
}
